﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Game.Server.Socket
{
    /// <summary> 
    /// 客户端会话类
    /// </summary> 
    public class Session
    {
        /// <summary> 
        /// 构造函数 
        /// </summary> 
        /// <param name="clientSocket">客户端Socket连接</param> 
        public Session(System.Net.Sockets.Socket clientSocket)
        {
            ClientSocket = clientSocket;
            ID = (int)ClientSocket.Handle;
        }

        /// <summary> 
        /// 退出类型枚举 
        /// </summary> 
        public enum ExitTypes
        {
            /// <summary>
            /// 正常退出
            /// </summary>
            Normal,

            /// <summary>
            /// 异常退出
            /// </summary>
            Exception
        }

        /// <summary> 
        ///会话ID 
        /// </summary> 
        public int ID { set; get; }

        /// <summary> 
        /// 客户端会话Socket对象 
        /// </summary> 
        public System.Net.Sockets.Socket ClientSocket { set; get; }

        /// <summary> 
        /// 客户端的退出类型 
        /// </summary> 
        public ExitTypes ExitType { get; set; }

        /// <summary> 
        /// Socket对象HashCode 
        /// </summary> 
        /// <returns></returns> 
        public override int GetHashCode()
        {
            return (int)ClientSocket.Handle;
        }

        /// <summary> 
        /// 对比传入的客户端会话是否为当前会话 
        /// </summary> 
        /// <param name="session">客户端会话</param> 
        /// <returns></returns> 
        public bool Equals(Session session)
        {
            return (int)ClientSocket.Handle == (int)session.ClientSocket.Handle;
        }

        /// <summary> 
        /// 返回Session对象特征 
        /// </summary> 
        /// <returns></returns> 
        public override string ToString()
        {
            return string.Format("Session:{0},IP:{1}", ID, ClientSocket.RemoteEndPoint.ToString());
        }

        /// <summary> 
        /// 关闭Socket会话 
        /// </summary> 
        public void Close()
        {
            ClientSocket.Shutdown(SocketShutdown.Both);//关闭数据接收和发送
            ClientSocket.Close();//清理资源
        }
    }
}
